<template>
	<view class="tutorHome">
	<!-- 根据 currentComponent 动态加载组件 -->
	    <Invite  :ossUrl="ossUrl" :assistantId="assistantId"  v-if="currentComponent === 'Invite'" />
	    <PersonalDetails :ossUrl="ossUrl" v-if="currentComponent === 'PersonalDetails'" />
	    <Dynamic :ossUrl="ossUrl" v-if="currentComponent === 'Dynamic'" />
	    <Order  :ossUrl="ossUrl" v-if="currentComponent === 'Order'" />
	    <My v-if="currentComponent === 'My'" />
		<tui-tabbar  @clickTabbar="clickTabbar"></tui-tabbar>
	</view>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from 'vuex'
	import { getLoginTutorInfo } from "@/http/api/tutor/tutor.js"
	import Invite from './invite/invite.vue'
	import Dynamic from './dynamic/dynamic.vue'
	import My from './my/my.vue'
	import Order from './order/order.vue'
	import Cache from '@/utils/cache'
	import PersonalDetails from './personalDetails/personalDetails.vue'
	export default {
		data() {
			return {
				top: 0, //标题图标距离顶部距离
				marginTp:0,
				assistantId:'',
				title: '',
				ossUrl:getApp().globalData.ossurl,//图片前缀
				currentComponent: 'Invite' // 默认显示邀约
			}
		},
		components: {
			PersonalDetails,
			Order,
			Invite,
			Dynamic,
			My
		},
		onLoad() {
			this.getUsrTutorDetails()
			this.checkauthorize()
		},
		methods: {
			...mapMutations(['changeTabItem','changeTabBar']),
			clickTabbar(detils){
				this.changeTabBar({index:detils.index})
				if(detils.index===0){
					this.currentComponent='Invite'
					this.title=''
				}else if(detils.index===1){
					this.currentComponent='Order'
					this.title='订单'
				}else if(detils.index===2){
					this.currentComponent='Dynamic'
					this.title='动态'
				}else{
					this.currentComponent='My'
					this.title='我的'
				}
			},
			// 定位授权
			checkauthorize() {
				let self = this

				// #ifdef MP-WEIXIN
				uni.getSetting({
					success(res) {
						if (!res.authSetting['scope.userLocation']) {
							uni.authorize({
								scope: 'scope.userLocation',
								success: () => { //这里是用户同意授权后的回调
									self.getLocation();
								},
								fail: () => { //这里是用户拒绝授权后的回调
									self.rejectSetting()
								}
							})
						} else { //用户已经授权过了
							self.getLocation();
						}
					}
				})
				// #endif

				// #ifdef APP-PLUS
				// APP端需要先检查权限
				this.checkAppLocationPermission();
				// #endif
			},

			// 检查APP位置权限
			checkAppLocationPermission() {
				// #ifdef APP-PLUS
				const self = this;
				// 获取当前系统信息
				const systemInfo = uni.getSystemInfoSync();
				// 判断是否是安卓系统
				const isAndroid = systemInfo.platform.toLowerCase() === 'android';

				if (isAndroid) {
					// 安卓平台需要动态申请权限
					const permissions = [
						'android.permission.ACCESS_FINE_LOCATION',
						'android.permission.ACCESS_COARSE_LOCATION'
					];

					plus.android.requestPermissions(
						permissions,
						function(resultObj) {
							// 检查是否有已授权的权限
							let hasLocationPermission = false;
							for (let i = 0; i < resultObj.granted.length; i++) {
								const grantedPermission = resultObj.granted[i];
								if (permissions.includes(grantedPermission)) {
									hasLocationPermission = true;
									break;
								}
							}

							if (hasLocationPermission) {
								// 有位置权限，获取位置
								self.getLocation();
							} else {
								// 没有位置权限，提示用户
								uni.showModal({
									title: '提示',
									content: '需要位置权限才能正常使用应用，请在设置中开启',
									confirmText: '去设置',
									success: function(res) {
										if (res.confirm) {
											// 打开应用设置页面
											self.openAppPermissionSettings();
										}
									}
								});
							}
						},
						function(error) {
							console.error('权限请求失败:', error);
						}
					);
				} else {
					// iOS平台直接请求位置权限
					self.getLocation();
				}
				// #endif

				// 非APP平台
				// #ifndef APP-PLUS
				this.getLocation();
				// #endif
			},

			// 打开应用权限设置页面
			openAppPermissionSettings() {
				// #ifdef APP-PLUS
				if (uni.getSystemInfoSync().platform.toLowerCase() === 'android') {
					// 安卓平台
					const Intent = plus.android.importClass("android.content.Intent");
					const Settings = plus.android.importClass("android.provider.Settings");
					const Uri = plus.android.importClass("android.net.Uri");
					const mainActivity = plus.android.runtimeMainActivity();
					const intent = new Intent();
					intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
					const uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
					intent.setData(uri);
					mainActivity.startActivity(intent);
				} else {
					// iOS平台
					const UIApplication = plus.ios.import("UIApplication");
					const application = UIApplication.sharedApplication();
					const NSURL = plus.ios.import("NSURL");
					const setting = NSURL.URLWithString("app-settings:");
					application.openURL(setting);
					plus.ios.deleteObject(setting);
					plus.ios.deleteObject(NSURL);
					plus.ios.deleteObject(application);
				}
				// #endif
			},

			// 获取当前定位的经纬度
			getLocation() {
				let self = this
				uni.getLocation({
					type: 'gcj02',
					success: function(res) {
						//经纬度转换成省市区 latitude纬度，long经度
						self.$utils.getAddress(res.latitude, res.longitude,
							'661f987dcae58c7cb089e589ad3c7b18', (obj) => {
								Cache.set('adressNmae', obj.name);
								Cache.set('city', obj.city);
						});
					},
					fail: (err) => {
						console.error('定位失败:', err);
						// #ifdef APP-PLUS
						// APP端定位失败，可能是权限问题，重新检查权限
						if (uni.getSystemInfoSync().platform.toLowerCase() === 'android') {
							self.checkAppLocationPermission();
						}
						// #endif
					}
				});
			},

			// 用户拒绝授权后的回调 (微信小程序)
			rejectSetting() {
				var that = this;
				uni.showModal({
					title: '警告',
					content: '授权失败，请打开位置消息授权',
					success: (res) => {
						if (res.confirm) { //去授权
							that.toOpenSetting();
						} else if (res.cancel) { //用户点击取消
							console.log(res);
							uni.showModal({
								title: '提示',
								content: '获取权限失败，将无法获取定位哦~',
								showCancel: false,
								success: (res) => {
									that.toOpenSetting();
								}
							})
						}
					}
				})
			},

			//打开微信设置页面 (微信小程序)
			toOpenSetting() {
				// #ifdef MP-WEIXIN
				uni.openSetting({
					success: (e) => {
						console.log(e);
					}
				})
				// #endif
			},
			getUsrTutorDetails(){
				getLoginTutorInfo().then(res=>{
					if(res.code===200){
						this.assistantId=res.data.id
						this.$store.commit('setUserTutorDetails',res.data)
					}
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
@import './tutorHome.scss';
</style>
